﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace LANmine
{
    public partial class SignupTeam : Form
    {
        private ListViewGame SelectedGame;
        private Language lmLang;
        private User lmUser;
        private Database roDb = new Database("ro");
        private Database rwDb = new Database("rw");
        private DataSet ds = new DataSet();

        public SignupTeam()
        {
            InitializeComponent();
        }

        public SignupTeam(ListViewGame sel, Language lmLang, User lmUser)
            : this()
        {
            // Save parameters
            this.SelectedGame = sel;
            this.lmLang = lmLang;
            this.lmUser = lmUser;

            // Apply Language Specification
            ApplyLanguage();

            // Load teams
            LoadTeams();

            // Fill in controls
            lblTeamSize.Text = this.SelectedGame.TeamSize + "v" + this.SelectedGame.TeamSize;
            lblGame.Text = this.SelectedGame.Name;
        }

        #region Language Specifications

        /// <summary>
        /// Overwrite all text properties of all elements in all forms with the right ones.
        /// </summary>
        private void ApplyLanguage()
        {
            //  Window Title 
            this.Text = this.lmLang.GetString("compos.btnRegister");

            // Header
            this.lblSignupTeam.Text = this.lmLang.GetString("compos.btnRegister");

            // Controls
            btnClose.Text = this.lmLang.GetString("mteam.btnClose");
            btnSignup.Text = this.lmLang.GetString("tsignup.btnSignup");

        }

        #endregion

        #region Member Functions

        /// <summary>
        /// Loads a list of teams into the class' DataSet
        /// </summary>
        public void LoadTeams()
        {
            SqlConnection dbConn = this.roDb.getDbConn();
            SqlDataAdapter da = new SqlDataAdapter("lmGetMemberTeams", dbConn);

            try
            {
                // Set as stored procedure 
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

                // Add Parameters 
                da.SelectCommand.Parameters.Add("@CaptId", SqlDbType.BigInt, 0);
                da.SelectCommand.Parameters["@CaptId"].Value = this.lmUser.ID;

                // Fill the DataSet from the DataAdapter's table 
                da.Fill(ds, "teams");

                // Get the teams table
                DataTable dt = ds.Tables["teams"];

                if (dt.Rows.Count > 0)
                {
                    //  DataTable is not empty, bind the control to the DataTable 
                    cboTeams.DisplayMember = "naam";
                    cboTeams.ValueMember = "id";
                    cboTeams.DataSource = dt;
                }
                else
                {
                    // DataTable is empty, add empty row and disable controls
                    cboTeams.Items.Add(lmLang.GetString("mteam.errNoTeams"));
                    btnSignup.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                // Show error 
                MessageBox.Show(lmLang.GetString("mteam.errLoadTeams") + "\n" + ex.Message);
            }
        }

        public void TeamSignup(UInt32 tId, UInt32 gId)
        {
            SqlConnection dbConn = this.rwDb.getDbConn();
            SqlDataAdapter daIns = new SqlDataAdapter("SELECT * FROM compos_teams_inschrijvingen", dbConn);
            SqlCommandBuilder cb = new SqlCommandBuilder(daIns);

            try
            {
                // Copy database schema
                daIns.FillSchema(ds, SchemaType.Source, "signup");

                // Request new row
                DataRow dr = ds.Tables["signup"].NewRow();

                // Assign data
                dr["team_id"] = tId;
                dr["game_id"] = gId;

                // Put the new row into the table
                ds.Tables["signup"].Rows.Add(dr);

                // Commit the changes
                daIns.Update(ds, "signup");
                 
            }
            catch (Exception ex)
            {
                // Failed to join game
                MessageBox.Show(lmLang.GetString("tsignup.errSignup") + "\n" + ex.Message);
            }
        }

        #endregion

        #region Event Handlers

        private void cboTeams_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataRow[] dr = ds.Tables["teams"].Select("id = " + cboTeams.SelectedValue);

            // Check if the selected team fulfills the requirements
            if (Convert.ToUInt32(dr[0]["members"]) == this.SelectedGame.TeamSize)
                btnSignup.Enabled = true;
            else
                btnSignup.Enabled = false;
        }

        private void btnSignup_Click(object sender, EventArgs e)
        {
            // Format message string
            String dText = String.Format(lmLang.GetString("tsignup.qrySignup"), this.SelectedGame.Name, ((DataRowView)cboTeams.SelectedItem)["naam"]);

            // Open dialog
            DialogResult dRes = MessageBox.Show(dText, lmLang.GetString("compos.btnRegister"), MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dRes == DialogResult.Yes)
            {
                // Sign up the selected team
                TeamSignup(Convert.ToUInt32(cboTeams.SelectedValue.ToString()), this.SelectedGame.ID);

                // Close the window
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        #endregion

    }
}
